<template>
  <page-view>
    <page-header title="注册" :show-back="true"></page-header>
    <div class="content-box">
      <Form @submit="onSubmit">
        <cell-group inset>
          <field
            v-model="nickName"
            name="昵称"
            label="昵称"
            placeholder="请输入昵称"
            :rules="[{ required: true, message: '请填写昵称' }]"
          />
          <field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <field
            v-model="confirm_password"
            type="password"
            name="重复密码"
            label="重复密码"
            placeholder="请输入密码"
            :rules="[{ validator: validatorPassword }]"
          />
          <field
            type="text"
            v-model="user_phone"
            label="电话"
            name="电话"
            placeholder="请输入电话"
            :rules="[{ required: true, message: '请填写电话号码' }]"
          />
          <field
            type="text"
            v-model="user_email"
            label="邮箱"
            name="邮箱"
            placeholder="请输入邮箱"
            :rules="[{ required: true, message: '请填写邮箱' }]"
          />
          <field name="radio" label="性别">
            <template #input>
              <radio-group v-model="user_sex" direction="horizontal">
                <radio name="男">男</radio>
                <radio name="女">女</radio>
              </radio-group>
            </template>
          </field>

          <field name="uploader" label="头像上传" v-model="user_photo">
            <template #input>
              <uploader
                v-model="fileList"
                :after-read="afterRead"
                :max-count="1"
                :max-size="500 * 1024"
                @oversize="onOversize"
              />
            </template>
          </field>
        </cell-group>

        <div style="margin: 16px">
          <Button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="正在注册"
            :disabled="loading"
          >
            提交
          </Button>
        </div>
      </Form>
    </div>
  </page-view>
</template>

<script>
import {
  Form,
  Field,
  CellGroup,
  Button,
  RadioGroup,
  Radio,
  Uploader,
  Toast,
} from "vant";
import Api from "../utils/api";
import { useRouter } from "vue-router";
import { reactive, toRefs, ref, getCurrentInstance } from "vue";
export default {
  name: "Register",
  components: {
    Form,
    Field,
    CellGroup,
    Button,
    RadioGroup,
    Radio,
    Uploader,
    Toast,
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    let userInfo = reactive({
      nickName: "",
      password: "",
      confirm_password: "",
      user_sex: "男",
      user_phone: "",
      user_email: "",
      //上传以后的地址
      user_photo: "",
    });

    //提交按钮 点击提交后 加载状态和禁用状态用loading表示
    let loading = ref(false);
    //文件上传的列表
    const fileList = ref([]);

    //校验重复密码
    const validatorPassword = () => {
      if (userInfo.password !== userInfo.confirm_password) {
        return "重复密码不对";
      }
    };

    //after-read	文件读取完成后的回调函数
    //头像读取成功后调用
    const afterRead = async (file) => {
      // 此时可以自行将文件上传至服务器
      file.status = "uploading";
      file.message = "上传中...";
      let results = await Api.userInfo.uploadUserPhoto(file.file);
      //拿到的结果是：图片上传后的 网络地址
      console.log("图片上传后的网络地址", results);
      console.log("图片读取成功后的图片信息对象", file);
      file.status = "done"; //上传成功
      //将组件图片用到的地址 改为上传成功后的网络地址
      fileList.value = [{ url: proxy.BaseURL + results, message: "上传成功" }];
      userInfo.user_photo = results;
    };

    //头像图片超过大小后触发
    const onOversize = (file) => {
      Toast.fail("文件大小不能超过500kb");
    };

    //表单提交
    const onSubmit = (value) => {
      //收集到所有填的表单数据
      console.log("submit", value);
      addUser();
    };
    const addUser = async () => {
      Toast.loading({
        message: "注册中",
        forbidClick: true,
        duration: 0,
      });
      loading.value = true;
      setTimeout(async () => {
        try {
          let results = await Api.userInfo.add(userInfo);
          console.log(results);
          Toast.clear(true);
          Toast.success("注册成功");
          router.replace({name:'Login'})
        } catch (error) {
            Toast.fail('注册失败');
        }finally{
            loading.value = false;
        }
      },2000);
    };

    return {
      ...toRefs(userInfo),
      onSubmit,
      validatorPassword,
      loading,
      fileList,
      afterRead,
      onOversize,
    };
  },
};
</script>

<style lang="scss" scoped>
</style>